<template>
  <div>
    <div id="map-container" style="height: 400px;"></div>
    <!-- <div v-if="positionName">位置名称：{{ positionName }}</div> -->
  </div>
</template>
 
<script>
import AMapLoader from '@amap/amap-jsapi-loader';
window._AMapSecurityConfig = {
  // 安全密钥
  securityJsCode: "b0f0e59862beb46c76468d1cdb118781",
};

export default {
  props: {
    defaultPosition: {
      type: Object,
      // default: null,
      required: true,
      willReadFrequently:true
    },
  },
  data() {
    return {

      position: this.defaultPosition,// 初始化位置
      map: null,
      marker: null,
      longitude: null,
      latitude: null,
      positionName: null,
      geoCoder: null,
    };
  },
  mounted() {
    this.initMap();
  },

  methods: {
    initMap() {
      AMapLoader.load({
        key: 'a25b21d06dbe2b0f1f7dcfaffd61bd77', // 替换为您的Web端开发者Key
        version: '2.0',
        plugins: ['AMap.Geocoder'],
      }).then((AMap) => {
        this.map = new AMap.Map('map-container', {
          zoom: 11,
          center: [114.351642, 34.801549],
          
        });

        this.geoCoder = new AMap.Geocoder();

        this.map.on('click', async (e) => {
          const { lng, lat } = e.lnglat;
          this.longitude = lng;
          this.latitude = lat;

          if (this.marker) {
            this.map.remove(this.marker);
          }

          this.marker = new AMap.Marker({
            position: [lng, lat],
          });

          this.map.add(this.marker);

          try {
            const result = await this.getAddress([lng, lat]);
            this.positionName = result.regeocode.formattedAddress;
            this.$emit('updatePosition', { longitude: lng, latitude: lat, positionName: this.positionName });
          } catch (e) {
            this.positionName = '无法获取位置名称';
          }


        });


        // 检查默认位置是否传递过来
        console.log(this.defaultPosition, '子组件初始化时接收到的默认位置数据a');
        // 根据经纬度显示地图标

        if (this.defaultPosition) {
          this.addMarker(this.defaultPosition);
        }

      }).catch((e) => {
        console.log(e);
      });
    },
    getAddress(lnglat) {
      return new Promise((resolve, reject) => {
        this.geoCoder.getAddress(lnglat, (status, result) => {
          if (status === 'complete' && result.regeocode) {
            resolve(result);
          } else {
            reject('无法获取位置名称');
          }
        });
      });
    },
    addMarker(position) {
      if (this.marker) {//检查地图上是否已经有一个标记
        this.map.remove(this.marker);
      }
      this.marker = new AMap.Marker({
        position: [position.longitude, position.latitude],
      });
      this.map.add(this.marker);
    },
  },
  watch: {
    defaultPosition: {
      handler(newValue) {
        this.addMarker(newValue);
      },
      deep: true
    }
  },
};
</script>